package by.siarhei.java.tij.reusing.exercises.ex09;

/**
 * @author Siarhei Shchahratsou <s.siarhei@gmail.com>
 * @since 12.03.14
 */
public class Root {
    Component1 cmp1;
    Component2 cmp2;
    Component3 cmp3;

    public Root() {
        System.out.println("Root");

        cmp1 = new Component1();
        cmp2 = new Component2();
        cmp3 = new Component3();
    }

    void dispose() {
        cmp1.dispose();
        cmp2.dispose();
        cmp3.dispose();

        System.out.println("dispose Root");
    }

    public static void main(String[] args) {
        Root r = new Stem();
        call(r, (Stem) r);

        //exercise 12
        r.dispose();
    }


    static void call(Root r, Stem s) {
        //!!! IT'S FALSE, because only methods are dynamically bound
        System.out.println(r.cmp1.equals(s.cmp1));
        System.out.println("Root: " + r.cmp1);
        System.out.println("Stem: " + s.cmp1);
    }
}

class Stem extends Root {
    Component1 cmp1;
    Component2 cmp2;
    Component3 cmp3;

    Stem() {
        System.out.println("Stem");

        cmp1 = new Component1();
        cmp2 = new Component2();
        cmp3 = new Component3();
    }

    void dispose() {
        cmp1.dispose();
        cmp2.dispose();
        cmp3.dispose();

        System.out.println("dispose Stem");

        super.dispose();
    }
}

class Component1 {
    Component1() {
        System.out.println("Component1");
    }

    void dispose() {
        System.out.println("dispose Component1");
    }
}

class Component2 {
    Component2() {
        System.out.println("Component2");
    }

    void dispose() {
        System.out.println("dispose Component2");
    }
}

class Component3 {
    Component3() {
        System.out.println("Component3");
    }

    void dispose() {
        System.out.println("dispose Component3");
    }
}
